<?php

namespace stlswm\WxSubscriptionPHP\Account;

use stlswm\WxSubscriptionPHP\CurlHttp;
use stlswm\WxSubscriptionPHP\Response;


/**
 * Class QRCode
 * 带参数二维码生成
 * https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1443433542
 * @package WxSubscriptionPHP\Account
 * @Date    2018/12/29
 * @Time    16:01
 */
class QRCode
{
    use CurlHttp;

    private static $api = 'https://api.weixin.qq.com/cgi-bin/qrcode/create';

    /**
     * @var int 该二维码有效时间，以秒为单位
     */
    public $expireSeconds = 0;

    /**
     * @var string 二维码类型
     */
    public $actionName = '';

    /**
     * @var string scene_id    场景值ID，临时二维码时为32位非0整型，永久二维码时最大值为100000（目前参数只支持1--100000）
     */
    public $sceneId = '';

    /**
     * @var string 场景值ID（字符串形式的ID）
     */
    public $sceneStr = '';

    /**
     * 创建
     * @param  string  $accessToken
     * @return Response
     * @Author wm
     * @Date   2018/12/29
     * @Time   16:06
     */
    public function create(string $accessToken): Response
    {
        if (empty($accessToken)) {
            $response = new Response();
            $response->result = false;
            $response->message = '参数$accessToken不能为空';
            return $response;
        }
        if (!in_array($this->actionName, ['QR_SCENE', 'QR_STR_SCENE', 'QR_LIMIT_SCENE', 'QR_LIMIT_STR_SCENE'])) {
            $response = new Response();
            $response->result = false;
            $response->message = '参数$actionName非法';
            return $response;
        }
        $url = self::$api."?access_token={$accessToken}";
        $actionInfo = [
            'scene' => [],
        ];
        switch ($this->actionName) {
            case 'QR_SCENE':
            case 'QR_LIMIT_SCENE':
                $actionInfo['scene'] = [
                    'scene_id' => $this->sceneId,
                ];
                break;
            case 'QR_STR_SCENE':
            case 'QR_LIMIT_STR_SCENE':
                $actionInfo['scene'] = [
                    'scene_str' => $this->sceneStr,
                ];
                break;
        }
        return self::postJson($url, [
            'expire_seconds' => (int)$this->expireSeconds,
            'action_name'    => (string)$this->actionName,
            'action_info'    => $actionInfo,
        ]);
    }

    /**
     * 通过ticket换取二维码
     * @param  string  $ticket
     * @return string
     * @Author wm
     * @Date   2018/12/29
     * @Time   16:05
     */
    public static function showQRCode(string $ticket): string
    {
        return 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.urlencode($ticket);
    }
}